// pages/work_experience/work_experience.js
const app = getApp(), core = require('../../utils/core'), util = require('../../utils/util'), WeValidator = require('../../utils/we-validator');
WeValidator.addRule('gt',{
  rule: function (value, fieldName) {
    console.log(this);
    return value > this.data[fieldName];
  },
});
Page({

  /**
   * 页面的初始数据
   */
  data: {
    finishTexts: ['未离职','已离职'],
    finish: null, //是否已经毕业, 判断是否显示毕业时间选择
  },


  bindFinishChange(event) {
    let finish = event.detail.value;
    if(finish==1) {
      this.setData({'model.end':'', finish});
    }else {
      this.setData({'model.end':'至今', finish});
    }
  },

  bindStartChange: function (e) {
    this.setData({'model.start':e.detail.value});
  },

  bindEndChange: function (e) {
    this.setData({'model.end':e.detail.value});
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({today: util.formatDatetime(new Date(), 'yyyy-mm')});
    this.getOpenerEventChannel().on('dataTransfer', data => {
      this.setData({
        model: Object.assign({},data.model), //创建一份浅拷贝, 不影响上一页的值
      });
      if(data.model.end!==undefined) {
        this.setData({finish: data.model.end==='至今'?'0':'1'});
      }
    });
  },

  bindSubmit(event) {
    let data = event.detail.value;
    let validator = new WeValidator({
      rules: {
        'job_title': {required: true},
        'start': {required: true},
        'end': {required: true, gt: 'start'},
        'company_name': {required: true},
        'detail': {required: true},
      },
      messages: {
        'job_title': {required: '请填写工作职位'},
        'start': {required: '请选择开始时间'},
        'end': {required: '请选择结束时间', gt: '结束时间必须大于开始时间'},
        'company_name': {required: '请填写公司名称'},
        'detail': {required: '请填写工作描述'},
      }
    });
    if (!validator.checkData(data)) {
      return;
    }
    data.module = 'work';
    core.post({
      url: 'xilujob.user/save_module', data: data,
      success: ret => {
        this.getOpenerEventChannel().emit('dataTransfer', {
          model: ret.data.model,
          complete_percent: ret.data.complete_percent
        });
        wx.navigateBack();
      }
    });
  }
});
